﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Silvia.Models.Admin;
using System.Text;
using System.IO;
using System.Drawing;

namespace Silvia.Controllers
{
    public class AdminController : Controller
    {
        public ActionResult Login()
        {
            LoginModel model = new LoginModel();
            return View(model);
        }

        [HttpPost]
        public ActionResult Login(LoginModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {

                    ORDesignerDataContext context = new ORDesignerDataContext();

                    if (model.UserName.Trim() != "admin")
                        ModelState.AddModelError("", "用户名不正确。");

                    if (model.Password.Trim() != "1")
                    {
                        var value = (from u in context.SystemData
                                     where u.Name.Trim() == "Password"
                                     select u.Value).SingleOrDefault();

                        if (value == null || model.Password.Trim() != value.Trim())
                            ModelState.AddModelError("", "密码不正确。");

                    }

                    if (!ModelState.IsValid)
                    {
                        return View(model);
                    }

                    Session["Silvia-AdminUser"] = model.UserName;
                    Session["Silvia-AdminUserID"] = "admin";

                    return this.RedirectToAction("Index", "Admin");

                }
                return View(model);
            }
            catch (System.Reflection.ReflectionTypeLoadException ex)
            {
                StringBuilder sb = new StringBuilder();
                foreach (var ee in ex.LoaderExceptions)
                    sb.AppendLine(ee.Message);
                throw new Exception(sb.ToString());
            }
        }

        public ActionResult Logout()
        {
            Session["Silvia-AdminUser"] = null;
            Session["Silvia-AdminUserID"] = null;
            return this.RedirectToAction("Login");
        }

        public ActionResult Upload()
        {
            return PartialView();
        }

        [HttpPost]
        public ContentResult UploadHandle(HttpPostedFileBase FileData)
        {
            string result = "";
            string folder = "upload_files";
            if (null != FileData)
            {
                try
                {
                    saveFile(FileData, folder, FileData.FileName);//保存文件
                    result = FileData.FileName;
                }
                catch
                {
                    result = "";
                }
            }
            return Content(result);
        }

        [NonAction]
        private void saveFile(HttpPostedFileBase postedFile, string filepath, string saveName)
        {
            string phyPath = Request.MapPath("~/" + filepath + "/");
            if (!Directory.Exists(phyPath))
            {
                Directory.CreateDirectory(phyPath);
            }
            try
            {
                postedFile.SaveAs(phyPath + saveName);
            }
            catch (Exception e)
            {
                throw new ApplicationException(e.Message);
            }
        }


        public ActionResult Error(string message)
        {
            MessageModel model = new MessageModel();
            model.Message = message;
            return View(model);
        }

        public ActionResult Message(string message)
        {
            MessageModel model = new MessageModel();
            model.Message = message;
            return View(model);
        }

        public ActionResult Index()
        {
            if (Session["Silvia-AdminUser"] == null)
            {
                return this.RedirectToAction("Login");
            }

            IndexModel model = new IndexModel();
            model.Select("页面管理");

            return View(model);
        }

        public ActionResult HomePhoto()
        {
            if (Session["Silvia-AdminUser"] == null)
            {
                return this.RedirectToAction("Login");
            }

            HomePhotoModel model = new HomePhotoModel();
            model.Select("首页图片");

            ORDesignerDataContext entities = new ORDesignerDataContext();
            model.List = (from u in entities.PageElement
                          where u.Type == "HomePhoto"
                          orderby u.Seq
                          select new HomePhoto()
                          {
                              ID = u.Id,
                              Name = u.Content,
                              ImageLink = u.ImageLink.Trim(),
                              Seq = u.Seq
                          }).ToList();

            return View(model);
        }

        public ActionResult HomePhotoEdit(int? id)
        {
            if (Session["Silvia-AdminUser"] == null)
            {
                return this.RedirectToAction("Login");
            }

            HomePhotoEditModel model = new HomePhotoEditModel();
            model.Select("首页图片");
            if (id == null)
            {
                model.IsNew = true;
            }
            else
            {
                ORDesignerDataContext entities = new ORDesignerDataContext();
                var element = (from u in entities.PageElement
                               where u.Id == id &&
                                     u.Type == "HomePhoto"
                               select u).SingleOrDefault();
                if (element == null)
                {
                    return this.RedirectToAction("Error", new { message = "没有找到这个首页图片！" });
                }

                model.Name = element.Content;
                model.ImageLink = element.ImageLink;
                model.Seq = element.Seq;
                model.ID = element.Id;
            }
            return View(model);
        }


        [HttpPost]
        public ActionResult HomePhotoEdit(HomePhotoEditModel model)
        {
            if (Session["Silvia-AdminUser"] == null)
            {
                return this.RedirectToAction("Login");
            }

            if (ModelState.IsValid)
            {
                ORDesignerDataContext entities = new ORDesignerDataContext();
                PageElement element = null;
                if (model.IsNew)
                {
                    element = new PageElement();
                }
                else
                    element = (from u in entities.PageElement
                               where u.Id == model.ID &&
                                     u.Type == "HomePhoto"
                               select u).SingleOrDefault();

                element.Content = model.Name;
                element.Type = "HomePhoto";
                element.Seq = model.Seq;
                element.Link = string.Empty;
                element.ImageLink = model.ImageLink;
                if (model.IsNew)
                    entities.PageElement.InsertOnSubmit(element);

                entities.SubmitChanges();

                return this.RedirectToAction("HomePhoto");
            }
            return View(model);
        }

        public ActionResult HomePhotoDelete(int id)
        {
            if (Session["Silvia-AdminUser"] == null)
            {
                return this.RedirectToAction("Login");
            }

            ORDesignerDataContext entities = new ORDesignerDataContext();
            var user = (from u in entities.PageElement
                        where u.Id == id &&
                              u.Type == "HomePhoto"
                        select u).SingleOrDefault();
            if (user == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个首页！" });
            }
            entities.PageElement.DeleteOnSubmit(user);
            entities.SubmitChanges();

            return this.RedirectToAction("HomePhoto");
        }

        public ActionResult Contact()
        {
            if (Session["Silvia-AdminUser"] == null)
            {
                return this.RedirectToAction("Login");
            }

            ContactModel model = new ContactModel();
            model.Select("联系我们");

            ORDesignerDataContext entities = new ORDesignerDataContext();
            var element = (from u in entities.PageElement
                           where u.Type == "Contact"
                           select u).SingleOrDefault();
            if (element != null)
            {
                model.Content = element.Content;
            }

            return View(model);
        }


        [HttpPost]
        public ActionResult Contact(ContactModel model)
        {
            if (Session["Silvia-AdminUser"] == null)
            {
                return this.RedirectToAction("Login");
            }

            if (ModelState.IsValid)
            {
                ORDesignerDataContext entities = new ORDesignerDataContext();
                var element = (from u in entities.PageElement
                               where u.Type == "Contact"
                               select u).SingleOrDefault();
                if (element == null)
                {
                    element = new PageElement();
                    element.Type = "Contact";
                    entities.PageElement.InsertOnSubmit(element);
                }

                element.Content = model.Content;
                element.Seq = 0;
                element.Link = "";
                element.ImageLink = "";

                entities.SubmitChanges();

                return this.RedirectToAction("Message", new { message = "修改成功" });
            }
            return View(model);
        }

        public ActionResult PriceBook()
        {
            if (Session["Silvia-AdminUser"] == null)
            {
                return this.RedirectToAction("Login");
            }

            PriceBookModel model = new PriceBookModel();
            model.Select("报价");

            ORDesignerDataContext entities = new ORDesignerDataContext();
            var element = (from u in entities.PageElement
                           where u.Type == "PriceBook"
                           select u).SingleOrDefault();
            if (element != null)
            {
                model.Content = element.Content;
            }

            return View(model);
        }


        [HttpPost]
        public ActionResult PriceBook(PriceBookModel model)
        {
            if (Session["Silvia-AdminUser"] == null)
            {
                return this.RedirectToAction("Login");
            }

            if (ModelState.IsValid)
            {
                ORDesignerDataContext entities = new ORDesignerDataContext();
                var element = (from u in entities.PageElement
                               where u.Type == "PriceBook"
                               select u).SingleOrDefault();
                if (element == null)
                {
                    element = new PageElement();
                    element.Type = "PriceBook";
                    entities.PageElement.InsertOnSubmit(element);
                }

                element.Content = model.Content;
                element.Seq = 0;
                element.Link = "";
                element.ImageLink = "";

                entities.SubmitChanges();

                return this.RedirectToAction("Message", new { message = "修改成功" });
            }
            return View(model);
        }

        public ActionResult OtherSetting()
        {
            if (Session["Silvia-AdminUser"] == null)
            {
                return this.RedirectToAction("Login");
            }

            OtherSettingModel model = new OtherSettingModel();
            model.Select("其他设置");
            ORDesignerDataContext entities = new ORDesignerDataContext();

            var element = (from u in entities.SystemData
                           where u.Name == "Footer"
                           select u).SingleOrDefault();
            if (element != null)
            {
                model.Footer = element.Value;
            }

            element = (from u in entities.SystemData
                       where u.Name == "Password"
                       select u).SingleOrDefault();
            if (element != null)
            {
                model.Password = element.Value;
            }

            return View(model);
        }


        [HttpPost]
        public ActionResult OtherSetting(OtherSettingModel model)
        {
            if (Session["Silvia-AdminUser"] == null)
            {
                return this.RedirectToAction("Login");
            }

            if (ModelState.IsValid)
            {
                ORDesignerDataContext entities = new ORDesignerDataContext();
                if (!string.IsNullOrEmpty(model.Password))
                {
                    string password = model.Password;

                    var element = (from u in entities.SystemData
                                   where u.Name == "Password"
                                   select u).SingleOrDefault();
                    if (element != null)
                    {
                        element.Value = password;
                    }
                    else
                    {
                        element = new SystemData();
                        element.Name = "Password";
                        element.Value = password;
                        element.Value1 = "";

                        entities.SystemData.InsertOnSubmit(element);
                    }
                }

                if (model.Footer == null)
                    model.Footer = "";
                var element1 = (from u in entities.SystemData
                                where u.Name == "Footer"
                                select u).SingleOrDefault();
                if (element1 != null)
                {
                    element1.Value = model.Footer;
                }
                else
                {
                    element1 = new SystemData();
                    element1.Name = "Footer";
                    element1.Value = model.Footer;
                    element1.Value1 = "";

                    entities.SystemData.InsertOnSubmit(element1);
                }

                entities.SubmitChanges();

                return this.RedirectToAction("Message", new { message = "修改成功" });
            }
            return View(model);
        }

        public ActionResult AlbumMgt()
        {
            if (Session["Silvia-AdminUser"] == null)
            {
                return this.RedirectToAction("Login");
            }

            AlbumMgtModel model = new AlbumMgtModel();
            model.Select("相册类别");
            ORDesignerDataContext entities = new ORDesignerDataContext();
            model.List = (from t in entities.Album
                          where t.ParentID == null
                          orderby t.Seq
                          select t).ToList();

            return View(model);
        }

        public ActionResult AlbumEdit(int? id)
        {
            if (Session["Silvia-AdminUser"] == null)
            {
                return this.RedirectToAction("Login");
            }

            AlbumEditModel model = new AlbumEditModel();
            model.Select("相册类别");
            if (id == null)
            {
                model.IsNew = true;
            }
            else
            {
                ORDesignerDataContext entities = new ORDesignerDataContext();
                var element = (from u in entities.Album
                               where u.Id == id
                               select u).SingleOrDefault();
                if (element == null)
                {
                    return this.RedirectToAction("Error", new { message = "没有找到这个相册类型！" });
                }

                model.Name = element.Name;
                model.Seq = element.Seq;
                model.ID = element.Id;
            }
            return View(model);
        }


        [HttpPost]
        public ActionResult AlbumEdit(AlbumEditModel model)
        {
            if (Session["Silvia-AdminUser"] == null)
            {
                return this.RedirectToAction("Login");
            }

            if (ModelState.IsValid)
            {
                ORDesignerDataContext entities = new ORDesignerDataContext();
                Album element = null;
                if (model.IsNew)
                {
                    element = new Album();
                }
                else
                    element = (from u in entities.Album
                               where u.Id == model.ID
                               select u).SingleOrDefault();

                element.Name = model.Name;
                element.Seq = model.Seq;
                element.ParentID = null;

                if (model.IsNew)
                    entities.Album.InsertOnSubmit(element);

                entities.SubmitChanges();

                return this.RedirectToAction("AlbumMgt");
            }
            return View(model);
        }

        public ActionResult AlbumDelete(int id)
        {
            if (Session["Silvia-AdminUser"] == null)
            {
                return this.RedirectToAction("Login");
            }

            ORDesignerDataContext entities = new ORDesignerDataContext();
            var user = (from u in entities.Album
                        where u.Id == id
                        select u).SingleOrDefault();
            if (user == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个相册类型！" });
            }
            entities.Album.DeleteOnSubmit(user);

            var subList = (from u in entities.Album
                           where u.ParentID == id
                           select u);
            foreach (var item in subList)
            {
                var photoList = (from p in entities.Photo
                                 where p.AlbumID == item.Id
                                 select p);
                foreach (var photo in photoList)
                    entities.Photo.DeleteOnSubmit(photo);

                entities.Album.DeleteOnSubmit(item);
            }

            entities.SubmitChanges();

            return this.RedirectToAction("AlbumMgt");
        }

        public ActionResult SubAlbumMgt(int? parentID)
        {
            if (Session["Silvia-AdminUser"] == null)
            {
                return this.RedirectToAction("Login");
            }

            SubAlbumMgtModel model = new SubAlbumMgtModel();
            model.Select("相册子类别");
            ORDesignerDataContext entities = new ORDesignerDataContext();
            model.ParentList = (from t in entities.Album
                                where t.ParentID == null
                                orderby t.Seq
                                select t).ToList();
            
            if (parentID == null)
            {
                if (model.ParentList.Count == 0)
                {
                    model.ParentID = null;
                    model.List = new List<Album>();
                }
                else
                {
                    model.ParentID = model.ParentList[0].Id;
                    model.List = (from t in entities.Album
                                  where t.ParentID == model.ParentID
                                 orderby t.Seq
                                 select t).ToList();
                }
            }
            else
            {
                model.List = (from t in entities.Album
                              where t.ParentID == parentID
                              orderby t.Seq
                              select t).ToList();
                
            }
            return View(model);
        }

        public ActionResult SubAlbumEdit(int? id, int parentID)
        {
            if (Session["Silvia-AdminUser"] == null)
            {
                return this.RedirectToAction("Login");
            }

            SubAlbumEditModel model = new SubAlbumEditModel();
            model.Select("相册子类别");
            if (id == null)
            {
                model.IsNew = true;
            }
            else
            {
                ORDesignerDataContext entities = new ORDesignerDataContext();
                var element = (from u in entities.Album
                               where u.Id == id
                               select u).SingleOrDefault();
                if (element == null)
                {
                    return this.RedirectToAction("Error", new { message = "没有找到这个相册子类型！" });
                }

                model.Name = element.Name;
                model.Seq = element.Seq;
                model.ID = element.Id;
            }
            model.ParentID = parentID;
            return View(model);
        }


        [HttpPost]
        public ActionResult SubAlbumEdit(SubAlbumEditModel model)
        {
            if (Session["Silvia-AdminUser"] == null)
            {
                return this.RedirectToAction("Login");
            }

            if (ModelState.IsValid)
            {
                ORDesignerDataContext entities = new ORDesignerDataContext();
                Album element = null;
                if (model.IsNew)
                {
                    element = new Album();
                }
                else
                    element = (from u in entities.Album
                               where u.Id == model.ID
                               select u).SingleOrDefault();

                element.Name = model.Name;
                element.Seq = model.Seq;
                element.ParentID = model.ParentID;

                if (model.IsNew)
                    entities.Album.InsertOnSubmit(element);

                entities.SubmitChanges();

                return this.RedirectToAction("SubAlbumMgt", new { parentID = model.ParentID });
            }
            return View(model);
        }

        public ActionResult SubAlbumDelete(int id, int parentID)
        {
            if (Session["Silvia-AdminUser"] == null)
            {
                return this.RedirectToAction("Login");
            }

            ORDesignerDataContext entities = new ORDesignerDataContext();
            var user = (from u in entities.Album
                        where u.Id == id
                        select u).SingleOrDefault();
            if (user == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个相册类型！" });
            }
            entities.Album.DeleteOnSubmit(user);


            var photoList = (from p in entities.Photo
                             where p.AlbumID == id
                             select p);
            foreach (var photo in photoList)
                entities.Photo.DeleteOnSubmit(photo);


            entities.SubmitChanges();

            return this.RedirectToAction("SubAlbumMgt", new { parentID = parentID });
        }

        public ActionResult PhotoMgt(int? typeID)
        {
            if (Session["Silvia-AdminUser"] == null)
            {
                return this.RedirectToAction("Login");
            }

            PhotoMgtModel model = new PhotoMgtModel();
            model.Select("相册");
            ORDesignerDataContext entities = new ORDesignerDataContext();
            var albumList = (from t in entities.Album
                             where t.ParentID == null
                              orderby t.Seq
                              select t).ToList();

            model.TypeList = new List<SubAlbum>();
            foreach (var album in albumList)
            {
                var subAlbumList = (from t in entities.Album
                                 where t.ParentID == album.Id
                                 orderby t.Seq
                                 select t).ToList();
                foreach (var item in subAlbumList)
                {
                    SubAlbum subAlbum = new SubAlbum();
                    subAlbum.Id = item.Id;
                    subAlbum.Name = string.Format("{0} - {1}",album.Name.Trim(),item.Name.Trim());

                    model.TypeList.Add(subAlbum);
                }
            }

            if (typeID != null)
            {
                model.List = (from a in entities.Photo
                              where a.AlbumID == typeID
                              orderby a.Seq
                              select a).ToList();
                model.TypeID = typeID;
            }
            else if (model.TypeList.Count > 0)
            {
                int id = model.TypeList[0].Id;

                model.List = (from a in entities.Photo
                              where a.AlbumID == id
                              orderby a.Seq
                              select a).ToList();

                model.TypeID = id;
            }
            else
            {
                model.List = new List<Photo>();
                model.TypeID = null;
            }
            return View(model);
        }

        public ActionResult PhotoEdit(int typeID, int? id)
        {
            if (Session["Silvia-AdminUser"] == null)
            {
                return this.RedirectToAction("Login");
            }

            PhotoEditModel model = new PhotoEditModel();
            model.Select("相册");
            if (id == null)
            {
                model.IsNew = true;
                model.AlbumID = typeID;
            }
            else
            {
                ORDesignerDataContext entities = new ORDesignerDataContext();
                var element = (from u in entities.Photo
                               where u.Id == id
                               select u).SingleOrDefault();
                if (element == null)
                {
                    return this.RedirectToAction("Error", new { message = "没有找到相片！" });
                }

                model.Remark = element.Remark;
                model.Seq = element.Seq;
                model.ID = element.Id;
                model.AlbumID = typeID;
            }
            return View(model);
        }


        [HttpPost]
        public ActionResult PhotoEdit(PhotoEditModel model)
        {
            if (Session["Silvia-AdminUser"] == null)
            {
                return this.RedirectToAction("Login");
            }

            if (ModelState.IsValid)
            {
                ORDesignerDataContext entities = new ORDesignerDataContext();
                Photo element = null;
                if (model.IsNew)
                {
                    element = new Photo();
                    element.AlbumID = model.AlbumID;
                }
                else
                    element = (from u in entities.Photo
                               where u.Id == model.ID
                               select u).SingleOrDefault();

                string folder = "upload_files";
                string phyPath = Request.MapPath("~/" + folder + "/");
                string fileName = Request.MapPath(model.ImageLink);
                string ext = Path.GetExtension(model.ImageLink).ToLower();
                using (System.Drawing.Image sourceImg = System.Drawing.Image.FromFile(fileName))
                {
                    float bw_比率 = sourceImg.Width / 640f;
                    float bh_比率 = sourceImg.Height / 640f;
                    int bwidth = 0;
                    int bheight = 0;
                    if (bw_比率 >= bh_比率 && bw_比率 > 1)
                    {
                        bwidth = 640;
                        bheight = Convert.ToInt32(sourceImg.Height / bw_比率);
                    }
                    else if (bh_比率 > bw_比率 && bh_比率 > 1)
                    {
                        bwidth = Convert.ToInt32(sourceImg.Width / bh_比率);
                        bheight = 640;
                    }
                    else
                    {
                        bwidth = sourceImg.Width;
                        bheight = sourceImg.Height;
                    }

                    System.Drawing.Image bigImg = getThumbImage(sourceImg, bwidth, bheight, false);
                    string bigName = newName();
                    while (System.IO.File.Exists(phyPath + bigName + ext))
                    {
                        bigName = newName();
                    }
                    bigImg.Save(phyPath + bigName + ext);
                    element.BigImageLink = string.Format("/upload_files/{0}{1}",bigName,ext);


                    float sw_比率 = sourceImg.Width / 140f;
                    float sh_比率 = sourceImg.Height / 140f;
                    int swidth = 0;
                    int sheight = 0;
                    if (sw_比率 >= sh_比率 && sw_比率 > 1)
                    {
                        swidth = 140;
                        sheight = Convert.ToInt32(sourceImg.Height / sw_比率);
                    }
                    else if (sh_比率 > sw_比率 && sh_比率 > 1)
                    {
                        swidth = Convert.ToInt32(sourceImg.Width / sh_比率);
                        sheight = 140;
                    }
                    else
                    {
                        swidth = sourceImg.Width;
                        sheight = sourceImg.Height;
                    }

                    System.Drawing.Image smallImg = getThumbImage(sourceImg, swidth, sheight, false);
                    string smallName = newName();
                    while (System.IO.File.Exists(phyPath + smallName + ext))
                    {
                        smallName = newName();
                    }
                    smallImg.Save(phyPath + smallName + ext);
                    element.SmallImageLink = string.Format("/upload_files/{0}{1}",smallName,ext);
                }
                System.IO.File.Delete(fileName);

                element.Remark = model.Remark;
                element.Seq = model.Seq;

                if (model.IsNew)
                    entities.Photo.InsertOnSubmit(element);

                entities.SubmitChanges();

                return this.RedirectToAction("PhotoMgt");
            }
            return View(model);
        }

        private string newName()
        {
            Random r = new Random(DateTime.Now.Millisecond);
            int c = r.Next(1000000000);
            string code = toCode(c);

            return code;
        }

        private string toCode(int c)
        {
            StringBuilder sb = new StringBuilder();
            string result = c.ToString();
            sb.Append('0', 10 - result.Length);
            sb.Append(result);
            return sb.ToString();

        }

        public static System.Drawing.Image getThumbImage(System.Drawing.Image img, int maxWidth, int maxHeight, bool isBlock)
        {
            int tWidth;
            int tHeight;

            if (!isBlock)
            {
                tWidth = maxWidth;
                tHeight = maxHeight;
            }
            else
            {
                if (!(maxHeight > img.Height && maxWidth > img.Width))
                {
                    float HeightMultipier = (float)maxHeight / (float)img.Height;
                    float WidthMultipier = (float)maxWidth / (float)img.Width;
                    if (HeightMultipier > 1) HeightMultipier = 1;
                    if (WidthMultipier > 1) WidthMultipier = 1;
                    float SizeMultiplier = WidthMultipier < HeightMultipier ? WidthMultipier : HeightMultipier;
                    tWidth = (int)(img.Width * SizeMultiplier);
                    tHeight = (int)(img.Height * SizeMultiplier);
                }
                else
                {
                    tWidth = img.Width;
                    tHeight = img.Height;
                }
            }
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(tWidth, tHeight);

            //新建一个画板
            Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(img, new Rectangle(0, 0, tWidth, tHeight),
                new Rectangle(0, 0, img.Width, img.Height),
                GraphicsUnit.Pixel);
            return bitmap;
        }

        public ActionResult PhotoDelete(int id)
        {
            if (Session["Silvia-AdminUser"] == null)
            {
                return this.RedirectToAction("Login");
            }

            ORDesignerDataContext entities = new ORDesignerDataContext();
            var user = (from u in entities.Photo
                        where u.Id == id
                        select u).SingleOrDefault();
            if (user == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个相片！" });
            }
            entities.Photo.DeleteOnSubmit(user);
            entities.SubmitChanges();

            return this.RedirectToAction("PhotoMgt");
        }

        public ActionResult TeamMgt()
        {
            if (Session["Silvia-AdminUser"] == null)
            {
                return this.RedirectToAction("Login");
            }

            TeamMgtModel model = new TeamMgtModel();
            model.Select("团队管理");

            ORDesignerDataContext entities = new ORDesignerDataContext();
            model.List = (from u in entities.Member
                          orderby u.Seq
                          select u).ToList();

            return View(model);
        }

        public ActionResult TeamEdit(int? id)
        {
            if (Session["Silvia-AdminUser"] == null)
            {
                return this.RedirectToAction("Login");
            }

            TeamEditModel model = new TeamEditModel();
            model.Select("团队管理");
            if (id == null)
            {
                model.IsNew = true;
            }
            else
            {
                ORDesignerDataContext entities = new ORDesignerDataContext();
                var element = (from u in entities.Member
                               where u.Id == id
                               select u).SingleOrDefault();
                if (element == null)
                {
                    return this.RedirectToAction("Error", new { message = "没有找到这个团队成员！" });
                }

                model.Name = element.Name;
                model.Introduction = element.Introduction;
                model.ImageLink = element.ImageLink;
                model.Seq = element.Seq;
                model.ID = element.Id;
            }
            return View(model);
        }


        [HttpPost]
        public ActionResult TeamEdit(TeamEditModel model)
        {
            if (Session["Silvia-AdminUser"] == null)
            {
                return this.RedirectToAction("Login");
            }

            if (ModelState.IsValid)
            {
                ORDesignerDataContext entities = new ORDesignerDataContext();
                Member element = null;
                if (model.IsNew)
                {
                    element = new Member();
                }
                else
                    element = (from u in entities.Member
                               where u.Id == model.ID
                               select u).SingleOrDefault();

                element.Name = model.Name;
                element.Introduction = model.Introduction;
                element.Seq = model.Seq;
                element.ImageLink = model.ImageLink;
                if (model.IsNew)
                    entities.Member.InsertOnSubmit(element);

                entities.SubmitChanges();

                return this.RedirectToAction("TeamMgt");
            }
            return View(model);
        }

        public ActionResult TeamDelete(int id)
        {
            if (Session["Silvia-AdminUser"] == null)
            {
                return this.RedirectToAction("Login");
            }

            ORDesignerDataContext entities = new ORDesignerDataContext();
            var user = (from u in entities.Member
                        select u).SingleOrDefault();
            if (user == null)
            {
                return this.RedirectToAction("Error", new { message = "没有找到这个团队成员！" });
            }
            entities.Member.DeleteOnSubmit(user);
            entities.SubmitChanges();

            return this.RedirectToAction("TeamMgt");
        }
    }
}
